﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using MayhemCore;
using System.Windows;
using MayhemWpf.ModuleTypes;
using MayhemWpf.UserControls;
using TwilioMayhem.Wpf;
using Twilio;

namespace TwilioMayhem.Reactions
{
    [DataContract]
    [MayhemModule("Twilio: Call telephone", "Calls a telephone")]
    public class Call : ReactionBase, IWpfConfigurable
    {
        public override void Perform()
        {
            CallTelephone(telephoneNumberTo, telephoneNumberFrom, voiceXmlUri, twilioSID, twilioToken);
        }

        private void CallTelephone(string telephoneNumberTo, string telephoneNumberFrom, string voiceXmlUri, string twilioSID, string twilioToken)
        {
            try
            {
                TwilioRestClient client = new TwilioRestClient(twilioSID, twilioToken);
                client.InitiateOutboundCall(telephoneNumberFrom, telephoneNumberTo, voiceXmlUri);
            }
            catch (Exception)
            {
                ;
            }
        }

        [DataMember]
        private string telephoneNumberTo;

        [DataMember]
        private string telephoneNumberFrom;

        [DataMember]
        private string voiceXmlUri;

        [DataMember]
        private string twilioSID;

        [DataMember]
        private string twilioToken;


        #region IWpfConfigurable Members

        public WpfConfiguration ConfigurationControl
        {
            get
            {
                return new CallConfig(telephoneNumberTo, telephoneNumberFrom, voiceXmlUri, twilioSID, twilioToken);
            }
        }

        public void OnSaved(WpfConfiguration configurationControl)
        {
            CallConfig config = configurationControl as CallConfig;
            telephoneNumberTo = config.TelephoneNumberTo;
            telephoneNumberFrom = config.TelephoneNumberFrom;
            voiceXmlUri = config.VoiceXmlUri;
            twilioSID = config.TwilioSID;
            twilioToken = config.TwilioToken;
        }

        #endregion

        #region IConfigurable Members

        public string GetConfigString()
        {
            return "Calls " + telephoneNumberTo;
        }

        #endregion
    }
}
